package user

import (
	"crypto/rand"
	"crypto/sha1"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"strconv"
	"time"
	"zhuandan/data_source"
	"zhuandan/models"
	"zhuandan/redis_lib"
)

func Xiansuolist(ctx *gin.Context) {
	var users []models.Xiansuo
	res := data_source.Db
	res.Order("RAND()").Find(&users)

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    users,
		"msg":     "ok",
	})
	return

}

type LogaddBody struct {
	Uid   int64  `json:"uid" gorm:"uid"`
	State int64  `json:"state" from:"state"`
	Url   string `json:"url" from:"url"`
}

func Logadd(ctx *gin.Context) {
	json1 := LogaddBody{}
	ctx.ShouldBind(&json1)
	uid := json1.Uid
	state := json1.State
	var title string
	if state == 1 {
		title = "访问页面1"
	} else if state == 2 {
		title = "访问页面2"
	} else if state == 2 {
		title = "访问页面3"
	}
	log := models.Logxs{
		Uid:     uid,
		Addtime: time.Now().Unix(),
		Title:   title,
	}
	data_source.Db.Create(&log)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return

}
func Xiangqing(ctx *gin.Context) {
	json1 := LogaddBody{}
	ctx.ShouldBind(&json1)
	uid := json1.Uid

	log := models.Logxs{
		Uid:     uid,
		Addtime: time.Now().Unix(),
		Title:   "点击访问详情",
	}
	data_source.Db.Create(&log)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return

}

type ConfigwxRBody struct {
	AppId     string `json:"appId"`
	Timestamp string `json:"timestamp"`
	NonceStr  string `json:"nonceStr"`
	Signature string `json:"signature"`
	Stringval string `json:"stringval"`
}

func Configwx(ctx *gin.Context) {
	json1 := LogaddBody{}
	ctx.ShouldBind(&json1)
	//state := json1.State
	url := json1.Url
	configwxtoken := Accesstoken()
	configwxjsapi, _ := redis_lib.Client.Get(ctx, "zhuandanconfigwxjsapi").Result()
	fmt.Println("configwxjsapi-------------", configwxjsapi)
	if configwxjsapi == "" || len(configwxjsapi) == 0 || configwxjsapi == "null" {
		jsapi := Accessjsapi(configwxtoken)
		redis_lib.Client.Set(ctx, "zhuandanconfigwxjsapi", jsapi, 7000*time.Second)
		configwxjsapi = jsapi
	}

	timeStamp := strconv.FormatInt(time.Now().Unix(), 10)
	nonceStr := RandUp(16)
	stringval := "jsapi_ticket=" + configwxjsapi + "&noncestr=" + nonceStr + "&timestamp=" + timeStamp + "&url=" + url
	//fmt.Println(stringval)
	data := []byte(stringval)
	hash := sha1.Sum(data)
	shastr := fmt.Sprintf("%x", hash)
	data1 := ConfigwxRBody{
		AppId:     appId,
		Timestamp: timeStamp,
		NonceStr:  nonceStr,
		Signature: shastr,
		Stringval: stringval,
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data1,
		"msg":     "ok",
	})
	return

}

func Configwxywd(ctx *gin.Context) {
	json1 := LogaddBody{}
	ctx.ShouldBind(&json1)
	//state := json1.State
	url := json1.Url
	configwxtoken := Accesstokengzhywd()
	configwxjsapi, _ := redis_lib.Client.Get(ctx, "yewudaoconfigwxjsapi").Result()
	//fmt.Println("configwxjsapi-------------", configwxjsapi)
	if configwxjsapi == "" || len(configwxjsapi) == 0 || configwxjsapi == "null" {
		jsapi := Accessjsapi(configwxtoken)
		redis_lib.Client.Set(ctx, "yewudaoconfigwxjsapi", jsapi, 7000*time.Second)
		configwxjsapi = jsapi
	}

	timeStamp := strconv.FormatInt(time.Now().Unix(), 10)
	nonceStr := RandUp(16)
	stringval := "jsapi_ticket=" + configwxjsapi + "&noncestr=" + nonceStr + "&timestamp=" + timeStamp + "&url=" + url
	//fmt.Println(stringval)
	data := []byte(stringval)
	hash := sha1.Sum(data)
	shastr := fmt.Sprintf("%x", hash)
	data1 := ConfigwxRBody{
		AppId:     appidywd,
		Timestamp: timeStamp,
		NonceStr:  nonceStr,
		Signature: shastr,
		Stringval: stringval,
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data1,
		"msg":     "ok",
	})
	return

}

var longLetters = []byte("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") // 61
// RandUp 随机字符串，包含 英文字母和数字附加=_两个符号
func RandUp(n int) string {
	if n <= 0 {
		return ""
	}
	b := make([]byte, n)
	arc := uint8(0)
	if _, err := rand.Read(b[:]); err != nil {
		return ""
	}
	for i, x := range b {
		arc = x & 61
		b[i] = longLetters[arc]
	}
	return string(b)
}

func Accessjsapi(token string) (data string) {
	resp, err := http.Get("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi&utm_source=yourwebset")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	r := ResponseOpenid{}
	fmt.Println(string(body))

	//把请求到的结构反序列化到专门接受返回值的对象上面
	err = json.Unmarshal(body, &r)
	if err != nil {
		fmt.Println(err)
	}
	weixintoken := r.Ticket

	return weixintoken
}
